<template>
  <div class="">
    <!--头部区域-->
    <header-component :border="true"></header-component>

    <!--返回区域-->
    <div class="back_area">
      <div class="left">
        <img src="@/assets/ship-detail-img/back.png">
        <div class="ship_name">Edit Shop</div>
      </div>
      <div class="right">
        <button @click="submit">Save</button>
      </div>
    </div>

    <div class="edit_ship_container">
      <!--底部区域-->
      <div v-if="shipDetail" class="bottom_area">
        <!--船舶照片区域-->
        <div class="photos_area">
          <div class="top_area">
            <div class="area_title">Photos</div>
            <div @click="triggerImgInput" class="upload_btn">
              <img src="@/assets/edit-ship/upload.png">
              <div>Upload Photo</div>
            </div>
          </div>
          <!-- 隐藏的文件输入 -->
          <input
            type="file"
            ref="imgInput"
            @change="handleImgChange"
            style="display: none;"
            multiple
            accept=".png,.jpg"
          >
          <!--照片墙区域-->
          <div v-if="shipDetailDto.shipIconImgList" class="items">
            <div v-for="(item,index) in shipDetailDto.shipIconImgList" :key="index" class="item">
              <img class="ship_img" :src="item">
              <!--删除按钮-->
              <div @click="deleteShipIconImg(item)" class="del_btn">
                <img class="del_img" src="@/assets/edit-ship/delete.png">
              </div>
            </div>
          </div>
        </div>
        <!--基础信息区域 Basic Information-->
        <div class="common_box">
          <div class="area_title">
            Basic Information
          </div>
          <div v-if="shipDetail" class="form_area">
            <div class="info_select_item">
              <div class="small-title">
                船型
              </div>
              <div class="info_value_item">
                <!--                <select-box-->
                <!--                  v-model="shipDetail.shipType"-->
                <!--                  :options="shipCategoryList"-->
                <!--                  labelKey="name"-->
                <!--                  valueKey="id"-->
                <!--                ></select-box>-->

                <el-tree-select
                  v-model="shipDetailDto.shipType"
                  :data="shipCategoryList"
                  check-strictly
                  :render-after-expand="false"
                  clearable
                  :props="{
    label: 'name',
    value: 'id',
    children: 'children'
  }"
                />
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Build Year
              </div>
              <div class="info_value_item">
                <select-box
                  v-model="shipDetailDto.yearOfBuild"
                  selectType="year"
                  :options="generateYearOptions()"
                ></select-box>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                船籍
              </div>
              <div class="info_value_item">
                <select-mul-box
                  v-model="shipDetailDto.shipNative"
                  :options="useDictStore().getDictionary('ship_native')"
                  labelKey="dictLabel"
                  valueKey="dictValue"
                ></select-mul-box>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                航区
              </div>
              <div class="info_value_item">
                <select-box
                  labelKey="dictLabel"
                  valueKey="dictValue"
                  v-model="shipDetailDto.navigationArea"
                  :options="useDictStore().getDictionary('navigation_area')"
                ></select-box>
              </div>
            </div>
          </div>
        </div>
        <!--租售信息区域 Lease / Sale Information-->
        <div class="common_box">
          <div class="area_title">
            Lease / Sale Information
          </div>
          <div class="form_area">
            <div class="info_select_item">
              <div class="small-title">
                * Rent / Sale
              </div>
              <div class="info_value_item">
                <select-mul-box
                  v-model="shipDetailDto.shipStatus"
                  :options="useDictStore().getDictionary('ship_status')"
                  labelKey="dictLabel"
                  valueKey="dictValue"
                ></select-mul-box>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                意向报价 (¥)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetailDto.intendedQuote"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                租约起止日期
              </div>
              <div class="info_value_item">
                <el-date-picker
                  prefix-icon=""
                  v-model="shipDetailDto.leaseDateRange"
                  type="daterange"
                  start-placeholder="Start"
                  end-placeholder="End"
                >
                </el-date-picker>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                租期
              </div>
              <div class="info_value_item">
                <input-number-box :min="0"
                                  :max="3"
                                  :step="1"
                                  :precision="0"
                                  placeholder="请输入数值" v-model="shipDetailDto.leaseTerm"></input-number-box>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                希望租约方式
              </div>
              <div class="info_value_item">
                <select-box
                  labelKey="dictLabel"
                  valueKey="dictValue"
                  v-model="shipDetailDto.preferredCharterType"
                  :options="useDictStore().getDictionary('lease_method')"
                ></select-box>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                现有租期合约
              </div>
              <div class="info_value_item">
                <select-box
                  labelKey="dictLabel"
                  valueKey="dictValue"
                  v-model="shipDetailDto.currentCharterContract"
                  :options="useDictStore().getDictionary('lease_method')"
                ></select-box>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                船舶动态
              </div>
              <div class="info_value_item">
                <select-box
                  labelKey="dictLabel"
                  valueKey="dictValue"
                  v-model="shipDetailDto.shipNews"
                  :options="useDictStore().getDictionary('ship_dynamics')"
                ></select-box>
              </div>
            </div>
          </div>
        </div>
        <!--船舶数据区域 Ship Data-->
        <div class="common_box">
          <div class="area_title">
            Ship Data
          </div>
          <div class="form_area">
            <div class="info_select_item">
              <div class="small-title">
                Deadweight (mt)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.deadWeight"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                GRT / NRT
              </div>
              <div class="info_value_item info_two_value_item">
                <input-box style="border-radius: 8px 0 0 8px" type="number" v-model="shipDetail.grt"/>
                <div class="line_box">
                  <div class="line"></div>
                </div>
                <input-box style="border-radius: 0px 8px 8px 0px" type="number" v-model="shipDetail.nrt"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                LOA (m)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.totalLength"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Breadth Moulded (m)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.mouldedBreadth"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Hull Depth (m)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.mouldedDepth"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Height (m)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.overallHeight"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Loaded Draft (m)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.draft"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Service Speed (kn)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.designSpeed"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Full Speed (kn)
              </div>
              <div class="info_value_item">
                <input-box type="number" v-model="shipDetail.designSpeed"/>
              </div>
            </div>
          </div>
        </div>
        <!--更多信息区域 More Information-->
        <div class="common_box">
          <div class="area_title">
            More Information
          </div>
          <div class="form_area">
            <div class="info_select_item">
              <div class="small-title">
                IMO No.
              </div>
              <div>
                <input-box v-model="shipDetailDto.imo"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                Flag
              </div>
              <div>
                <input-box v-model="shipDetailDto.chess"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                主机数量
              </div>
              <div>
                <input-box v-model="shipDetailDto.numberOfEngines"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                主机品牌
              </div>
              <div>
                <input-box type="number" v-model="shipDetailDto.engineBrand"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                主机功率
              </div>
              <div class="info_value_item">
                <input-box v-model="shipDetailDto.enginePower"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                建造国家
              </div>
              <div>
                <input-box v-model="shipDetailDto.countryOfBuild"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                建造城市
              </div>
              <div>
                <input-box v-model="shipDetail.cityOfBuild"/>
              </div>
            </div>
            <div class="info_select_item">
              <div class="small-title">
                建造船厂
              </div>
              <div>
                <input-box v-model="shipDetailDto.shipyardOfBuild"/>
              </div>
            </div>
          </div>
        </div>
        <!--文档列表区域 Documents-->
        <div class="documents_box">
          <div class="area_title">
            <div>Documents</div>
            <div @click="triggerFileInput" class="upload_btn">
              <img src="@/assets/edit-ship/upload.png">
              <div>Add Document</div>
            </div>
            <!-- 隐藏的文件输入 -->
            <input
              type="file"
              ref="fileInput"
              @change="handleFileChange"
              style="display: none;"
              multiple
              accept=".pdf,.doc,.docx"
            >
          </div>
          <div class="items">
            <div v-for="(item,index) in originalDocumentList" class="item">
              <div class="left">
                <img src="@/assets/ship-detail-img/document.png">
                <div>{{ item.name }}</div>
              </div>
              <div class="right">
                <img src="@/assets/edit-ship/look.png">
                <img @click="delDocument(item)" src="@/assets/edit-ship/delete_gray.png">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {Swiper, SwiperSlide} from "swiper/vue";
import {useRouter, useRoute} from 'vue-router'
import {onMounted, ref} from "vue"
import ShipApI from "@/api/ship/index.js";
import {ResultEnum} from "@/enums/ResultEnum.js";
import SearchShipApi from "@/api/search-ship/index.js";
import {useDictStore} from "@/store/index.js";
import CommonApI from "@/api/common/index.js";

const router = useRouter()  // 用于编程式导航
const route = useRoute()    // 用于获取当前路由信息


const sid = ref() //船舶详情id
const shipDetail = ref({
  leaseDateRange: null
})

const shipDetailDto = ref({
  anonymizedShipProfileList: [], //船舶文档数组
  shipIconImgList: [],
  leaseDateRange: []
})

onMounted(() => {
  if (route.query.sid) {
    sid.value = route.query.sid
    toGetShipDetail()
    // 获取船舶文档列表
    queryShipDocumentParam.value.sid = sid.value
    toGetShipDocumentList()
    toGetShipCategoryList();
  }
})

//获取船舶详情
async function toGetShipDetail() {
  let res = await ShipApI.getShipDetail({sid: sid.value})
  if (res.code === ResultEnum.SUCCESS) {
    shipDetail.value = res.data
    shipDetailDto.value = res.data
    console.log(shipDetailDto.value, "shipDetailDto.value")

    if (shipDetail.value.shipType) {
      let arr = shipDetail.value.shipType.split(",")
      shipDetailDto.value.shipType = parseInt(arr[arr.length - 1])
    }

    shipDetailDto.value.leaseDateRange = [new Date(shipDetail.value.leaseStartDate), new Date(shipDetail.value.leaseEndDate)]

    if (shipDetail.value.anonymizedShipProfile) {
      shipDetailDto.value.anonymizedShipProfileList = shipDetail.value.anonymizedShipProfile.split(",")
    }
    if (shipDetail.value.shipIconImg) {
      shipDetailDto.value.shipIconImgList = shipDetail.value.shipIconImg.split(",")
    }
  }
}


/**
 * 船舶文档列表相关
 * */
const queryShipDocumentParam = ref({
  pageNum: 1, pageSize: 1000, category: "original", sid: null
})

const originalDocumentList = ref([])

//获取船舶文档列表 暂定一个原始
async function toGetShipDocumentList() {
  let res = await ShipApI.getShipDocumentList(queryShipDocumentParam.value)
  if (res.code === ResultEnum.SUCCESS) {
    originalDocumentList.value = res.rows
  }
}

const shipCategoryList = ref([]); //船舶分类列表 树形

//获取船舶分类列表
async function toGetShipCategoryList() {
  let res = await SearchShipApi.getShipCategoryList({pageNum: 1, pageSize: 1000});
  if (res.code == ResultEnum.SUCCESS) {
    shipCategoryList.value = res.rows;
  }
}


function generateYearOptions() {
  const currentYear = new Date().getFullYear();
  const endYear = currentYear + 10; // 当前年份后10年
  const startYear = 1900;
  const years = [];

  for (let year = startYear; year <= endYear; year++) {
    years.push({
      label: `${year}年`, // 显示为"2023年"格式
      value: year, // 值为数字年份
    });
  }

  return years;
}



async function submit() {
  shipDetail.value = shipDetailDto.value
  //处理船舶图片
  if (shipDetailDto.value.shipPhotoSeriesList) {
    shipDetail.value.shipPhotoSeries = shipDetailDto.value.shipPhotoSeriesList.join(",")
  }

  //处理船舶文档
  if (shipDetailDto.value.anonymizedShipProfileList) {
    shipDetail.value.anonymizedShipProfile = shipDetailDto.value.anonymizedShipProfileList.join(",")
  }

  //处理船舶图片
  if (shipDetailDto.value.shipIconImgList) {
    shipDetail.value.shipIconImg = shipDetailDto.value.shipIconImgList.join(",")
  }


  //处理 leaseStartDate和leaseEndDate
  const storableRange = shipDetailDto.value.leaseDateRange.map(date => date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-'));

  shipDetail.value.leaseStartDate = storableRange[0]
  shipDetail.value.leaseEndDate = storableRange[1]

  console.log(shipDetail.value, "最终提交")
  let res = await ShipApI.updateShip(shipDetail.value)
  if(res.code == ResultEnum.SUCCESS){
    ElMessage.success("修改成功")
  }
}

//删除文档
async function delDocument(item) {
  ElMessageBox.confirm('是否删除该文档?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    //调用删除接口
    let res = await ShipApI.delDocument(item.id)
    if (res.code == ResultEnum.SUCCESS) {
      ElMessage.success("删除成功")
      toGetShipDocumentList()
    } else {
      ElMessage.error("删除失败")
    }
  })
}

//文件列表改变
const fileInput = ref(null);

function handleFileChange(e) {
  const files = event.target.files;

  if (files.length > 0) {
    saveDocuments(files);
  }

  console.log(files, "files")
}

// 触发文件选择对话框
const triggerFileInput = () => {
  fileInput.value.click();
};

async function saveDocuments(files) {
  // this.uploading = true
  const delayBetweenUploads = 1000; // 1秒间隔
  let delay = 0;
  let uploadPromises = [];
  let successfulUploads = [];

  console.log(files, "files")

  let fileList = Array.from(files);

  // 创建上传任务数组
  for (const [index, item] of fileList.entries()) {
    const uploadPromise = new Promise((resolve) => {
      setTimeout(async () => {
        try {
          let formData = new FormData();
          formData.append("file", item);
          let res = await CommonApI.upload(formData);
          originalDocumentList.value.push({
            category: "original",
            filePath: res.url,
            sid: sid.value,
            name: item.name,
            type: item.type
          })

          if (res.code == 200) {
            ElMessage.success(`文件 ${index + 1}/${originalDocumentList.value.length} 上传成功`);
            successfulUploads.push(item); // 记录成功上传的文件
            resolve(true);
          } else {
            console.error(`文件 ${index + 1} 上传失败:`, res.message);
            resolve(false);
          }
        } catch (error) {
          console.error(`文件 ${index + 1} 上传失败:`, error);
          resolve(false);
        }
      }, delay);
    });

    uploadPromises.push(uploadPromise);
    delay += delayBetweenUploads;
  }

  // 等待所有上传完成
  const uploadResults = await Promise.all(uploadPromises);

  // 检查是否所有文件都上传成功
  const allSuccess = uploadResults.every(result => result === true);

  try {
    // 调用批量保存接口
    const saveRes = await ShipApI.saveShipDocumentList(originalDocumentList.value);

    if (saveRes.code === 200) {
      ElMessage.success("所有文件上传并保存成功");
      // this.uploading = false
      toGetShipDocumentList()
    } else {
      ElMessage.error("文件上传成功，但保存失败: " + saveRes.msg);
    }
  } catch (error) {
    ElMessage.error("调用批量保存接口失败: " + error.message);
  }
}


/**
 * 图片上传相关
 * */
// 触发文件选择对话框
const triggerImgInput = () => {
  imgInput.value.click();
};

const imgInput = ref(null);
function handleImgChange(e){
  const files = event.target.files;
  if (files.length > 0) {
    uploadImg(files);
  }
  console.log(files, "files")
}


//删除掉一个图
function deleteShipIconImg(item){
  shipDetailDto.value.shipIconImgList.splice(shipDetailDto.value.shipIconImgList.indexOf(item),1)
}

async function uploadImg(files) {
  // this.uploading = true
  const delayBetweenUploads = 1000; // 1秒间隔
  let delay = 0;
  let uploadPromises = [];
  let successfulUploads = [];

  console.log(files, "files")

  let fileList = Array.from(files);

  // 创建上传任务数组
  for (const [index, item] of fileList.entries()) {
    const uploadPromise = new Promise((resolve) => {
      setTimeout(async () => {
        try {
          let formData = new FormData();
          formData.append("file", item);
          let res = await CommonApI.upload(formData);
          shipDetailDto.value.shipIconImgList.push(res.url)

          if (res.code == 200) {
            ElMessage.success(`文件 ${index + 1}/${originalDocumentList.value.length} 上传成功`);
            successfulUploads.push(item); // 记录成功上传的文件
            resolve(true);
          } else {
            console.error(`文件 ${index + 1} 上传失败:`, res.message);
            resolve(false);
          }
        } catch (error) {
          console.error(`文件 ${index + 1} 上传失败:`, error);
          resolve(false);
        }
      }, delay);
    });

    uploadPromises.push(uploadPromise);
    delay += delayBetweenUploads;
  }
}



</script>

<style lang="scss" scoped>

.form_area {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 两列等宽 */
  gap: 16px;
  row-gap: 0;
  flex-wrap: wrap;

  ::v-deep .el-date-editor {
    width: 100%;
    height: 100%;
    background: #F0F2F7;
    padding: 0px 12px;
    border-radius: 8px;
    box-sizing: border-box;
    box-shadow: none;

    .el-range__icon {
      width: 0;
    }
  }

  ::v-deep .el-range-input {
    box-shadow: none;
    font-size: 14px;
    font-weight: normal;
    line-height: 20px;
    letter-spacing: normal;
    color: #1C1E24;
    text-align: left;
  }

  ::v-deep .el-range-input::placeholder {
    font-size: 14px;
    line-height: 20px;
    color: #808690;
  }

  ::v-deep .el-select__wrapper {
    width: 100%;
    height: 100%;
    background: #F0F2F7;
    padding: 0px 12px;
    border-radius: 8px;
    box-sizing: border-box;
    box-shadow: none;
  }

  ::v-deep .el-select__placeholder {
    font-size: 14px;
    line-height: 20px;
    color: #1C1E24;
  }

  .small-title {
    font-size: 14px;
    line-height: 20px;
    color: #808690;
    margin-bottom: 8px;
  }
}

.common_box {
  margin-bottom: 48px;

  .info_select_item {
    width: 248px;
    margin-bottom: 16px;

    .info_value_item {
      height: 32px;
    }

    .info_two_value_item {
      display: flex;
      align-items: center;
    }

    .line_box {
      background-color: #F0F2F7;
      height: 100%;
      display: flex;
      align-items: center
    }

    .line {
      width: 1px;
      background-color: #C8CAD2;
      height: 12px;
    }

  }
}

.common_box:last-child {
  margin-bottom: 0;
}

.documents_box {
  .area_title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
  }

  .upload_btn {
    display: flex;
    align-items: center;
    font-size: 12px;
    line-height: 16px;
    color: #1C1E24;

    img {
      width: 16px;
      height: 16px;
      margin-right: 4px;
    }
  }

  .items {
    .item {
      font-size: 14px;
      line-height: 20px;
      color: #808690;
      padding: 10px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #F0F2F7;

      img {
        width: 20px;
        height: 20px;
      }

      .left {
        display: flex;
        align-items: center;

        img {
          margin-right: 8px;
        }
      }

      .right {
        display: flex;
        align-items: center;

        img {
          margin-left: 16px;
        }
      }
    }
  }
}

.back_area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #FFFFFF;
  box-sizing: border-box;
  border-bottom: 1px solid #EAECF2;
  padding: 12px 24px;

  img {
    width: 24px;
    height: 24px;
  }

  .left {
    display: flex;
    align-items: center;

    .ship_name {
      font-size: 20px;
      font-weight: bold;
      line-height: 32px;
      color: #1C1E24;
      display: flex;
      align-items: center;
    }

    span {
      padding: 4px 8px;
      z-index: 1;
      background: #D1F7D2;
      font-size: 12px;
      line-height: 16px;
      color: #3D3D3D;
      margin-left: 8px;
      border-radius: 4px;
    }

    .star {
      width: 24px;
      height: 24px;
    }
  }

  .right {
    button {
      width: 106px;
      height: 32px;
      border-radius: 8px;
      opacity: 1;
      background: #1e90ff;
      color: #fff;
    }
  }
}

.area_title {
  font-size: 18px;
  font-weight: bold;
  line-height: 24px;
  color: #1C1E24;
  margin-bottom: 16px;
}

.edit_ship_container {
  padding: 24px 120px;
}

.photos_area {
  width: 100%;
  margin-bottom: 45px;

  .top_area {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .upload_btn {
    display: flex;
    align-items: center;
    font-size: 12px;
    font-weight: normal;
    line-height: 16px;
    color: #1C1E24;

    img {
      width: 16px;
      height: 16px;
      margin-right: 4px;
    }
  }

  .items {
    width: 100%;
    margin-top: 16px;
    display: grid;
    grid-template-columns: repeat(4, 1fr); /* 两列等宽 */
    gap: 16px;
    row-gap: 0;

    .item {
      position: relative;
      width: 248px;
      height: 140px;
      border-radius: 8px;

      .ship_img {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        object-fit: contain;
        border-radius: 8px;
      }

      .del_btn {
        position: absolute;
        right: 12px;
        top: 12px;
        background-color: rgba(0, 0, 0, .5);
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;

        .del_img {
          width: 16px;
          height: 16px;
          margin: 0 auto;
        }
      }
    }
  }
}
</style>
